﻿using System.Windows;
using System.Windows.Input;
using MaxStoreErp.Core.Commands;
using MaxStoreErp.Core.Interfaces;
using MaxStoreErp.Core.Ui.Drop;
using MaxStoreShop.Core.Contracts;
using MaxStoreShop.Core.EditorBase;
using MaxStoreShop.Core.Interception;
using MaxStoreShop.Domain.Directories;
using MaxStoreShop.Logic.ServicesContracts.Directories;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.WarehouseModule.Characters.CharacterEditor
{
    class CharacterEditorPresenter : EditorPresenterBase<CharacterEditorView, CharacterEditorViewModel, Character>, ICharacterEditor
    {
        [Dependency]
        public ICharacterService CharacterService { get; set; }

        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.BrowsePhotoCommand = new RelayCommand(ChangePhoto, () => ViewModel.SelectedItem != null);
            ViewModel.ClearPhotoCommand = new RelayCommand(ClearPhoto,
                () => ViewModel.SelectedItem != null && ViewModel.SelectedItem.Photo != null);
        }

        protected override void OnViewSet()
        {
            base.OnViewSet();
            View.CharacterImageBorder.OnDropItem = OnDropItem;
            View.Loaded += ViewOnLoaded;
        }

        void OnDropItem(DropItem dropItem)
        {
            ViewModel.SelectedItem.Photo = DroppedFileHelper.GetDroppedFile(dropItem, Container.Resolve<ISettings>().TempFolder);
        }

        void ViewOnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            View.SecondNameTextBox.Focus();
            Keyboard.Focus(View.SecondNameTextBox);
        }

        public override void OnViewClosed()
        {
            base.OnViewClosed();
            View.Loaded -= ViewOnLoaded;
            View.CharacterImageBorder.OnDropItem = null;
        }

        protected override void OnSave()
        {
            base.OnSave();
            CharacterService.SaveCharacter(ViewModel.SelectedItem);
            Container.Resolve<IDocumentManager>().Back();
        }

        void ClearPhoto()
        {
            ViewModel.SelectedItem.Photo = null;
        }

        void ChangePhoto()
        {
            var image = Container.Resolve<IPhotoHelper>().BrowseAndLoadPhoto();
            if (image == null)
                return;

            ViewModel.SelectedItem.Photo = image;
        }

        public void CreateNewCharacter()
        {
            ViewModel.SelectedItem = new Character();
            Container.Resolve<IDocumentManager>().NavigateTo(GetDocumentView());
        }
    }
}
